package com.wangzemin.leetcode.num811;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> visitTimes = new HashMap<String, Integer>();
        for (String cpdomain : cpdomains) {
            String[] domainCount = cpdomain.split("\\s");
            assert domainCount.length == 2;
            int count = Integer.parseInt(domainCount[0]);
            String domain = domainCount[1];
            visitTimes.put(domain, count + visitTimes.getOrDefault(domain, 0));

            int index = 0;
            while ((index=domain.indexOf(".",0))>0){
                domain = domain.substring(index+1);
                visitTimes.put(domain, count + visitTimes.getOrDefault(domain, 0));
            }
        }
        List<String> subdomainVisits = new ArrayList<>();
        for (String key:visitTimes.keySet()) {
            subdomainVisits.add(visitTimes.get(key)+" "+key);
        }
        return subdomainVisits;
    }
}